from datetime import datetime
import time
import urllib2
import urllib
import hashlib
from timezones.fields import TimeZoneField, MAX_TIMEZONE_LENGTH

from django.conf import settings
from django.contrib.auth.models import User as DjangoUser
from django.db import models
#from django.utils.functional import cached_property
import caching.base

from lib.jsonfield import JSONField


DEFAULT_BADGE = 'badge-default.png'
DEFAULT_INETEST = 0.12

class ModelBase(caching.base.CachingMixin, models.Model):
    """Common base model for all MDN models: Implements caching."""

    objects = caching.base.CachingManager()

    class Meta:
        abstract = True


class UserProfile(ModelBase):
    """
    The UserProfile *must* exist for each
    django.contrib.auth.models.User object. 
    """

    # Website fields defined for the profile form
    # TODO: Someday this will probably need to allow arbitrary per-profile
    # entries, and these will just be suggestions.

    user_display_name = models.CharField(_(u'Name'), max_length=255, default='',
                                blank=True)

    #user = models.OneToOneField(settings.AUTH_USER_MODEL)
    user = models.OneToOneField(settings.DjangoUser)
    """
       Represents a user.
       Ref:
       https://docs.djangoproject.com/en/1.6/ref/contrib/auth/#django.contrib.auth.models.User
       https://docs.djangoproject.com/en/1.6/topics/auth/customizing/
       https://docs.djangoproject.com/en/1.6/topics/auth/default/
    """

    is_verified = models.BooleanField(default=False)
    user_trustinfo = JSONField(blank=True, null=True)
    """
    trustinfo:
    {
      ...
      organization
      location
      sex
      asset
    }
    """

    """
    @property
    def websites(self):
        if 'websites' not in self.misc:
            self.misc['websites'] = {}
        return self.misc['websites']

    @websites.setter
    def websites(self, value):
        self.misc['websites'] = value

    @cached_property
    def beta_tester(self):
        return (constance.config.BETA_GROUP_NAME in
                self.user.groups.values_list('name', flat=True))
    """
    
    def badge_url(self, secure=True,ext='.jpg'):
        """Produce a gravatar image URL from username."""
        
        base_url = (secure and MEDIA_URL_S or MEDIA_URL)
        m=DEFAULT_BADGE
        if self.is_verified:
            m=hashlib.md5(self.user.username.lower().encode('utf8'))+ext
        return '%s/%s' % (base_url,m)
    
    @property
    def badge(self):
        return badge_url()


def create_user_profile(sender, instance, created, **kwargs):
    if created and not kwargs.get('raw', False):
        p, created = UserProfile.objects.get_or_create(user=instance)

#models.signals.post_save.connect(create_user_profile, sender=DjangoUser)


def parse_date(date_str):
    try:
        parsed_date = datetime.strptime(date_str, "%m/%d/%Y")
        parsed_date.strftime("%Y-%m-%d")
        return parsed_date
    except:
        return None


FIELD_MAP = {
    "date": ["Start Date", None, parse_date],
    "end_date": ["End Date", None, parse_date],
    "conference": ["Conference", None],
    "conference_link": ["Link", None],
    "location": ["Location", None],
    "people": ["Attendees", None],
    "description": ["Description", None],
    "done": ["Done", None],
    "materials": ["Materials URL", None],
}


def parse_header_line(header_line):
    for field_name in FIELD_MAP.keys():
        field = FIELD_MAP[field_name]
        if field[1] == None:
            try:
                FIELD_MAP[field_name][1] = header_line.index(field[0])
            except IndexError:
                FIELD_MAP[field_name][1] = ''
            except ValueError:
                FIELD_MAP[field_name][1] = ''


class EventLog(ModelBase):
    """
    Log for Event
    eventid,userid,money_putin
    """
    def addlog(self):
      pass

    def dellog(self):
      pass

class Event(ModelBase):
    """An event"""
    
    owner = models.ForeignKey(DjangoUser)
    
    """
    {
        {
            userID:userid
            money_putin:int_money
        }
    }
    """
    follower = JSONField(blank=True, null=True)
    
    money_goal = models.PositiveIntegerField()
    money_achieved = models.PositiveIntegerField()
    money_interset = models.FloatField(default=DEFAULT_INETEST)
    
    """
    money_startdate : the date pay to owner,complete_date+1DAY
    money_end_date  : the date owner pay out,>money_startdate
    money_deadline_date  : the date owner *MUST* pay out, money_startdate + money_duration
    money_duration  : DAYS
    money_paydate_prediction  :  money_deadline_date+1DAY
    """
    money_startdate = models.DateField()
    money_end_date = models.DateField()
    money_deadline_date = models.DateField()
    money_duration = models.PositiveIntegerField()
    money_paydate_prediction = models.DateField()
    
    """for event gathering"""
    start_date = models.DateField()
    end_date = models.DateField()
    description = models.TextField()
    rank = models.FloatField(default=1)
    is_offical_trust = models.BooleanField(default=False)
    offical_adv = models.TextField()
    
    is_closed = models.BooleanField(default=False)
    
    is_complete = models.BooleanField(default=False)
    complete_date = models.DateField()
    
    
    def attend(self,userID):
        pass
    
    def abort(self,userID):
        if not self.is_closed:
            pass



